<template>
  <el-card class="form-container" shadow="never">
    <div v-for="(cate, index) in allResourceCate" :class="index === 0 ? 'top-line' : null" :key="'cate' + cate.id">
      <el-row class="table-layout" style="background: #f2f6fc">
        <el-checkbox v-model="cate.checked" :indeterminate="isIndeterminate(cate.id as number)" @change="handleCheckAllChange(cate)">
          {{ cate.name }}
        </el-checkbox>
      </el-row>
      <el-row class="table-layout">
        <el-col :span="8" v-for="resource in getResourceByCate(cate.id as number)" :key="resource.id" style="padding: 4px 0">
          <el-checkbox v-model="resource.checked" @change="handleCheckChange(resource)">
            {{ resource.name }}
          </el-checkbox>
        </el-col>
      </el-row>
    </div>
    <div style="margin-top: 20px" align="center">
      <el-button type="primary" @click="handleSave()">保存</el-button>
      <el-button @click="handleClear()">清空</el-button>
    </div>
  </el-card>
</template>

<script setup lang="ts">
import { fetchAllResourceList } from '@/api/resource'
import { listAllCate } from '@/api/resourceCategory'
import { allocResource, listResourceByRole } from '@/api/role'
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import type { Resource } from '@/models/resource'
import type { ResourceCategory } from '@/models/resourceCategory'

interface ResourceCategoryParams extends ResourceCategory {
  checked?: boolean
}

defineOptions({ name: 'AllocResource' })
const route = useRoute()
const router = useRouter()
const roleId = ref(0)
const allResource = ref<Resource[]>([])
const allResourceCate = ref<ResourceCategoryParams[]>([])
roleId.value = Number(route.query.roleId)
getAllResourceCateList()

async function getAllResourceList() {
  const response = await fetchAllResourceList()
  allResource.value = response.data.data
  for (let i = 0; i < allResource.value.length; i++) {
    allResource.value[i].checked = false
  }
  getResourceByRole(roleId.value)
}

async function getAllResourceCateList() {
  const response = await listAllCate()
  allResourceCate.value = response.data.data
  allResourceCate.value.forEach((item) => {
    item.checked = false
  })
  getAllResourceList()
}

function getResourceByCate(categoryId: number): Resource[] {
  let cateResource = []
  if (allResource.value == null) return []
  for (let i = 0; i < allResource.value.length; i++) {
    let resource = allResource.value[i]
    if (resource.categoryId === categoryId) {
      cateResource.push(resource)
    }
  }
  return cateResource
}

async function getResourceByRole(roleId: number) {
  const response = await listResourceByRole(roleId)
  let allocResource = response.data.data
  allResource.value.forEach((item) => {
    item.checked = getResourceChecked(item.id as number, allocResource)
  })
  allResourceCate.value.forEach((item) => {
    item.checked = isAllChecked(item.id as number)
  })
}

function getResourceChecked(resourceId: number, allocResource: Resource[]) {
  if (allocResource == null || allocResource.length === 0) return false
  for (let i = 0; i < allocResource.length; i++) {
    if (allocResource[i].id === resourceId) {
      return true
    }
  }
  return false
}

function isIndeterminate(categoryId: number) {
  let cateResources = getResourceByCate(categoryId)
  if (cateResources == null) return false
  let checkedCount = 0
  for (let i = 0; i < cateResources.length; i++) {
    if (cateResources[i].checked === true) {
      checkedCount++
    }
  }
  return !(checkedCount === 0 || checkedCount === cateResources.length)
}

function isAllChecked(categoryId: number) {
  let cateResources = getResourceByCate(categoryId)
  if (cateResources == null) return false
  let checkedCount = 0
  for (let i = 0; i < cateResources.length; i++) {
    if (cateResources[i].checked === true) {
      checkedCount++
    }
  }
  if (checkedCount === 0) {
    return false
  }
  return checkedCount === cateResources.length
}

async function handleSave() {
  let checkedResourceIds = new Set()
  if (allResource.value != null && allResource.value.length > 0) {
    allResource.value.forEach((item) => {
      if (item.checked) {
        checkedResourceIds.add(item.id)
      }
    })
  }
  let params = {
    roleId: roleId.value,
    resourceIds: Array.from(checkedResourceIds).join(','),
  }
  await allocResource(params)
  ElMessage.success('分配成功')
  router.back()
}

function handleClear() {
  allResourceCate.value.forEach((item) => {
    item.checked = false
  })
  allResource.value.forEach((item) => {
    item.checked = false
  })
}

function handleCheckAllChange(cate: ResourceCategoryParams) {
  let cateResources = getResourceByCate(cate.id as number)
  for (let i = 0; i < cateResources.length; i++) {
    cateResources[i].checked = cate.checked
  }
}

function handleCheckChange(resource: Resource) {
  allResourceCate.value.forEach((item) => {
    if (item.id === resource.categoryId) {
      item.checked = isAllChecked(resource.categoryId as number)
    }
  })
}
</script>

<style scoped>
.table-layout {
  padding: 20px;
  border-left: 1px solid #dcdfe6;
  border-right: 1px solid #dcdfe6;
  border-bottom: 1px solid #dcdfe6;
}

.top-line {
  border-top: 1px solid #dcdfe6;
}
</style>
